import { getCategoryList } from '@/api/ClassManage';
import { pageContext } from '@/pages/boss/Listing/Plantemp/Wait/AddEditNew';
import { useAppSelector } from '@/redux/store';
import type { CascaderProps, FormItemProps } from 'antd';
import { Cascader } from 'antd';
import { FC, MutableRefObject, useContext, useEffect, useRef, useState } from 'react';
import IconFont from '../IconFont';

async function getClassViewData(entId?: string, page?: string) {
  const { data } = await getCategoryList(entId || undefined, page || undefined);
  return (
    data.list
      // .filter((oneLevel) => oneLevel.lowerListVo && oneLevel.lowerListVo.length)
      .map((oneLevel) => {
        return {
          label: (
            <div className="flexr alc jub">
              <div>{oneLevel.className}</div>
              {process.env.processEnvDetail.REACT_APP_PLATFORM === 'boss' && oneLevel.aiLearnClassification == 1 ? (
                <IconFont type="icon-AI" style={{ color: '#FF6D3B', fontSize: 16, marginLeft: 10, marginRight: 0 }} />
              ) : null}
            </div>
          ),
          value: oneLevel.guid,
          children:
            oneLevel.lowerListVo?.map((twoLevel) => {
              return {
                label: twoLevel.className,
                value: twoLevel.guid,
              };
            }) ?? [],
          disabled: !oneLevel.lowerListVo || oneLevel.lowerListVo.length === 0,
        };
      })
  );
}

type Options = Awaited<ReturnType<typeof getClassViewData>>;

type CategoryCascaderProps = { onSuccess?(data: Options): void } & CascaderProps;
type CategoryCascaderComponent = FC<CategoryCascaderProps> & {
  useFieldLevelTwo(initValue?: [string, string]): [FormItemProps, MutableRefObject<[string, string] | undefined>];
};

const CategoryCascader = function CategoryCascader({ value, disabled, onSuccess, ...props }: CategoryCascaderProps) {
  const [loading, setLoad] = useState(false);
  const [options, setOptions] = useState<Options>();
  const { entId } = useAppSelector((state) => state.loginEnt);
  const page = useContext(pageContext); // 默认defaultTemp,待上架计划模板过来的为：planTemp
  useEffect(() => {
    // if (!loading && !options) {
    setLoad(true);
    getClassViewData(entId, page)
      .then((data) => {
        setOptions(data);
        onSuccess?.(data);
      })
      .finally(() => {
        setLoad(false);
      });
    // }
  }, []); //onSuccess, loading, options
  return (
    <Cascader
      value={options ? value : undefined}
      disabled={loading || disabled}
      loading={loading}
      options={options}
      placeholder="请选择所属分类"
      {...props}
    />
  );
} as CategoryCascaderComponent;

CategoryCascader.useFieldLevelTwo = function (initValue?: [string, string]) {
  const ref = useRef<[string, string] | undefined>(initValue);
  return [
    {
      // 获取
      getValueFromEvent(value: [string, string]) {
        if (value && value.length === 2) {
          ref.current = value;
          return value[1];
        }
        return value;
      },
      // 回显
      getValueProps(value) {
        if (typeof value === 'string' && ref.current) {
          return {
            value: ref.current,
          };
        }
        return {
          value,
        };
      },
    },
    ref,
  ];
};

export { CategoryCascader, getClassViewData };
